package cn.hhz.ivos.dict.service.impl;

import cn.hhz.ivos.base.response.PageData;
import cn.hhz.ivos.base.utils.CacheUtils;
import cn.hhz.ivos.dict.mapper.DictMapper;
import cn.hhz.ivos.dict.pojo.dto.DictQuery;
import cn.hhz.ivos.dict.pojo.dto.DictSaveParam;
import cn.hhz.ivos.dict.pojo.entity.Dict;
import cn.hhz.ivos.dict.pojo.vo.DictVO;
import cn.hhz.ivos.dict.service.DictService;
import cn.hhz.ivos.dictoption.mapper.DictOptionMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DictServiceImpl implements DictService {

    @Autowired
    DictMapper dictMapper;
    @Autowired
    DictOptionMapper dictOptionMapper;
    @Autowired
    CacheUtils cacheUtils;

    @Override
    public PageData selectDict(DictQuery dictQuery) {
        List<DictVO> list = dictMapper.selectDict(dictQuery);
        //准备PageData对象用来装返回给前端的数据
        PageData dictData = new PageData();
        //向PageData对象中装存入当前页字典数据
        dictData.setList(list);
        //向PageData对象中装存入总记录数
        dictData.setTotal(dictMapper.selectDictCount(dictQuery));
        //返回封装好的对象
        return dictData;
    }

    @Override
    public void saveDict(DictSaveParam dictSaveParam) {
        log.debug("保存字典业务：dictSaveParam",dictSaveParam);
        Dict dict = new Dict();
        BeanUtils.copyProperties(dictSaveParam,dict);
        if(dict.getId()==null) {
            dict.setCreateTime(new Date());
            dictMapper.saveDict(dict);
        }else {
            dict.setUpdateTime(new Date());
            dictMapper.update(dict);
        }
    }

    @Override
    public void deleteDict(Long id) {
        log.debug("删除字典业务:id={}", id);
        //同时清空redis中与该字典相关的缓存数据
        DictQuery dict=new DictQuery();
        dict.setId(id);
        List<DictVO> dictVOList=dictMapper.selectDict(dict);
        if(dictVOList!=null && dictVOList.size()>0){
            DictVO dictVO = dictVOList.get(0);
            //根据dict的code删除之前的redis缓存
            cacheUtils.delete("dictOption"+dictVO.getCode());
        }
        dictMapper.deleteById(id);
        //删除字典，字典下的所有字典项也要随之删除
        dictOptionMapper.deleteByDictId(id);
    }
}
